package com.hspedu.newData.dmsxl.动态规划.基础;

import org.junit.Test;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-06 
 * @Version: 1.0
 */

public class LC1493删除一个元素以后全为1的最长子数组 {

    // todo
    // 动态规划
    public int longestSubarray1(int[] nums) {

        int len = nums.length;
        int[][] dp = new int[len][2];
        dp[0][1] = nums[0];
        for (int i = 1; i < len; i++) {
            dp[i][0] = dp[i-1][1];
            dp[i][1] = Math.max(dp[i-1][0] + nums[i],dp[i-1][1] + nums[i]);
        }


        return dp[len-1][0];
    }

    // todo
    // 滑动窗口
    public int longestSubarray(int[] nums) {
        int count = 0;
        int slow = 0;
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0){
                count++;
            }
            while (count > 1){
                if (nums[slow++] == 0){
                    count--;
                }
            }
            max = Math.max(max,i-slow-count+1);
        }
        if (count == 0){
            max--;
        }
        return max;
    }

    @Test
    public void test() {
        // 测试代码

        longestSubarray(new int[]{1,1,0,1});
        longestSubarray(new int[]{0,1,1,1,0,1,1,0,1,0,1});
        longestSubarray(new int[]{1,1,1});
    }
}
